<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="详细地址或GPS坐标" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入详细地址或GPS坐标"
          clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="负责人ID" prop="managerId">
        <el-input v-model="queryParams.managerId" placeholder="请输入负责人ID" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="最大存储容量" prop="capacity">
        <el-input
          v-model="queryParams.capacity"
          placeholder="请输入最大存储容量"
          clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="${comment}" prop="createdAt">
        <el-date-picker
          clearable
          v-model="queryParams.createdAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择${comment}">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="${comment}" prop="updatedAt">
        <el-date-picker
          clearable
          v-model="queryParams.updatedAt"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择${comment}">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['point:point:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['point:point:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['point:point:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['point:point:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table border stripe v-loading="loading" :data="pointList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="回收点唯一ID"
        align="center"
        width="110"
        prop="pointId"
        v-if="columns[0].visible"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="详细地址或GPS坐标"
        align="center"
        prop="location"
        width="200"
        v-if="columns[1].visible"
        :show-overflow-tooltip="true">
        <template #default="scope">
          <el-button @click="handleUpdate(scope.row, 'detail')" type="text">{{ scope.row.location }}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="负责人ID"
        align="center"
        prop="managerId"
        v-if="columns[2].visible"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="最大存储容量"
        align="center"
        prop="capacity"
        v-if="columns[3].visible"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="状态：active(正常)/maintenance(维护)/closed(关闭)"
        align="center"
        prop="status"
        width="210"
        v-if="columns[4].visible"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        width="180"
        v-if="columns[5].visible"
        :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更改时间"
        align="center"
        prop="updatedAt"
        width="180"
        v-if="columns[6].visible"
        :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="210" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Search"
            @click="handleUpdate(scope.row, 'detail')"
            v-hasPermi="['point:point:edit']"
            >详情</el-button
          >
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['point:point:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['point:point:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改回收站点信息对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body destroyOnClose>
      <el-form ref="pointRef" :model="form" :rules="rules" label-width="120px" label-position="top">
        <el-form-item label="详细地址或GPS坐标" prop="location">
          <el-input
            v-model="form.location"
            placeholder="请输入详细地址或GPS坐标"
            :disabled="title === '查看详情' ? true : false" />
        </el-form-item>
        <t-map
          v-if="title === '查看详情' ? false : true"
          :location="{
            address: form.location
          }" />
        <t-map
          v-else
          @locationUpdate="handleLocationUpdate"
          :disabled="true"
          :navigation="{
            current: currentLocation,
            destination: { lat: form.latitude, lng: form.longitude }
          }"></t-map>
        <el-form-item label="负责人ID" prop="managerId">
          <el-input
            v-model="form.managerId"
            placeholder="请输入负责人ID"
            :disabled="title === '查看详情' ? true : false" />
        </el-form-item>
        <el-form-item label="最大存储容量" prop="capacity">
          <el-input
            v-model="form.capacity"
            placeholder="请输入最大存储容量"
            :disabled="title === '查看详情' ? true : false" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Point">
import { listPoint, getPoint, delPoint, addPoint, updatePoint } from '@/api/point/point'
import TMap from '@/components/TMap/index.vue'
import { getLocation } from '../../../api/map'

const { proxy } = getCurrentInstance()

const pointList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const currentLocation = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    location: null,
    managerId: null,
    capacity: null,
    status: null,
    createdAt: null,
    updatedAt: null
  },
  rules: {
    location: [{ required: true, message: '详细地址或GPS坐标不能为空', trigger: 'blur' }],
    capacity: [{ required: true, message: '最大存储容量不能为空', trigger: 'blur' }],
    status: [
      { required: true, message: '状态：active(正常)/maintenance(维护)/closed(关闭)不能为空', trigger: 'change' }
    ],
    createdAt: [{ required: true, message: '$comment不能为空', trigger: 'blur' }],
    updatedAt: [{ required: true, message: '$comment不能为空', trigger: 'blur' }]
  },
  //表格展示列
  columns: [
    { key: 0, label: '回收点唯一ID', visible: true },
    { key: 1, label: '详细地址或GPS坐标', visible: true },
    { key: 2, label: '负责人ID', visible: true },
    { key: 3, label: '最大存储容量', visible: true },
    { key: 4, label: '状态：active(正常)/maintenance(维护)/closed(关闭)', visible: true },
    { key: 5, label: '${comment}', visible: true },
    { key: 6, label: '${comment}', visible: true }
  ]
})

const { queryParams, form, rules, columns } = toRefs(data)

/** 查询回收站点信息列表 */
function getList() {
  loading.value = true
  listPoint(queryParams.value).then(response => {
    pointList.value = response.rows
    total.value = response.total
    loading.value = false
  })
  getLocation(import.meta.env.VITE_APP_MAP_KEY).then(res => {
    currentLocation.value = res.data.result.location
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    pointId: null,
    location: null,
    managerId: null,
    capacity: null,
    status: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm('pointRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.pointId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加回收站点信息'
}

/** 修改按钮操作 */
function handleUpdate(row, detail) {
  reset()

  const _pointId = row.pointId || ids.value
  getPoint(_pointId).then(response => {
    form.value = response.data
    open.value = true
    if (detail) {
      title.value = '查看详情'
    } else {
      title.value = '修改回收站点信息'
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['pointRef'].validate(valid => {
    if (valid) {
      if (form.value.pointId != null) {
        updatePoint(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addPoint(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _pointIds = row.pointId || ids.value
  proxy.$modal
    .confirm('是否确认删除回收站点信息编号为"' + _pointIds + '"的数据项？')
    .then(function () {
      return delPoint(_pointIds)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'point/point/export',
    {
      ...queryParams.value
    },
    `point_${new Date().getTime()}.xlsx`
  )
}
function handleLocationUpdate(location) {
  if (location.formatted_addresses) {
    const { standard_address, recommend } = location.formatted_addresses
    form.value.address = `${standard_address} ${recommend}`
  }
  form.value.latitude = location.location.lat
  form.value.longitude = location.location.lng
}

getList()
</script>
